<template>
  <div class="users-management">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="page-actions">
        <button @click="showAddUserModal" class="btn btn-primary">
          <i class="fas fa-user-plus"></i> 添加新用户
        </button>
        <button @click="showImportModal = true" class="btn btn-secondary">
          <i class="fas fa-file-import"></i> 批量导入
        </button>
        <button
          @click="exportUsers"
          class="btn btn-secondary"
          :disabled="selectedUsers.length === 0 && !isAllSelected"
        >
          <i class="fas fa-file-export"></i> 导出
        </button>
        <button
          @click="confirmBatchDelete"
          class="btn btn-danger"
          :disabled="selectedUsers.length === 0"
        >
          <i class="fas fa-trash"></i> 批量删除
        </button>
      </div>
    </div>

    <div class="filter-section">
      <div class="search-box">
        <input
          v-model="searchQuery"
          placeholder="搜索用户..."
          @input="debouncedSearch"
          aria-label="搜索用户"
        />
        <i class="fas fa-search"></i>
      </div>
      <div class="filter-controls">
        <select
          v-model="roleFilter"
          class="role-filter"
          aria-label="按角色筛选"
        >
          <option value="">所有角色</option>
          <option value="学生">学生</option>
          <option value="教师">教师</option>
          <option value="管理员">管理员</option>
        </select>
        <select
          v-model="statusFilter"
          class="status-filter"
          aria-label="按状态筛选"
        >
          <option value="">所有状态</option>
          <option value="活跃">活跃</option>
          <option value="禁用">禁用</option>
        </select>
        <button @click="resetFilters" class="btn btn-sm btn-outline">
          <i class="fas fa-redo"></i> 重置筛选
        </button>
      </div>
    </div>

    <div class="table-container">
      <div v-if="isLoading" class="loading-overlay">
        <div class="spinner">
          <i class="fas fa-circle-notch fa-spin"></i>
        </div>
        <p>加载中...</p>
      </div>

      <div class="table-responsive">
        <table>
          <thead>
            <tr>
              <th class="checkbox-column">
                <label class="checkbox-container">
                  <input
                    type="checkbox"
                    :checked="isAllSelected"
                    @change="toggleSelectAll"
                    aria-label="选择所有用户"
                  >
                  <span class="checkmark"></span>
                </label>
              </th>
              <th @click="sortBy('id')" class="sortable">
                ID
                <i v-if="sortColumn === 'id'" :class="getSortIconClass('id')"></i>
              </th>
              <th @click="sortBy('username')" class="sortable">
                用户名
                <i v-if="sortColumn === 'username'" :class="getSortIconClass('username')"></i>
              </th>
              <th @click="sortBy('email')" class="sortable">
                邮箱
                <i v-if="sortColumn === 'email'" :class="getSortIconClass('email')"></i>
              </th>
              <th @click="sortBy('role')" class="sortable">
                角色
                <i v-if="sortColumn === 'role'" :class="getSortIconClass('role')"></i>
              </th>
              <th @click="sortBy('status')" class="sortable">
                状态
                <i v-if="sortColumn === 'status'" :class="getSortIconClass('status')"></i>
              </th>
              <th @click="sortBy('createdAt')" class="sortable">
                创建时间
                <i v-if="sortColumn === 'createdAt'" :class="getSortIconClass('createdAt')"></i>
              </th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in paginatedUsers" :key="user.id" :class="{ 'selected-row': isSelected(user.id) }">
              <td class="checkbox-column">
                <label class="checkbox-container">
                  <input
                    type="checkbox"
                    :checked="isSelected(user.id)"
                    @change="toggleSelect(user.id)"
                    :aria-label="`选择用户 ${user.username}`"
                  >
                  <span class="checkmark"></span>
                </label>
              </td>
              <td>{{ user.id }}</td>
              <td>
                <div class="user-info">
                  <div class="avatar" :style="{ backgroundColor: getAvatarColor(user.username) }">
                    {{ getUserInitials(user.username) }}
                  </div>
                  <span>{{ user.username }}</span>
                </div>
              </td>
              <td>{{ user.email }}</td>
              <td><span :class="getRoleClass(user.role)">{{ user.role }}</span></td>
              <td><span :class="getStatusClass(user.status)">{{ user.status }}</span></td>
              <td>{{ formatDate(user.createdAt) }}</td>
              <td>
                <div class="action-buttons">
                  <button @click="viewUserDetails(user)" class="btn btn-sm btn-info" title="查看详情" aria-label="查看用户详情">
                    <i class="fas fa-eye"></i>
                  </button>
                  <button @click="editUser(user)" class="btn btn-sm btn-secondary" title="编辑用户" aria-label="编辑用户">
                    <i class="fas fa-edit"></i>
                  </button>
                  <button @click="resetPassword(user.id)" class="btn btn-sm btn-warning" title="重置密码" aria-label="重置用户密码">
                    <i class="fas fa-key"></i>
                  </button>
                  <button @click="toggleUserStatus(user)" class="btn btn-sm" :class="user.status === '禁用' ? 'btn-success' : 'btn-danger'" :title="user.status === '禁用' ? '启用用户' : '禁用用户'" :aria-label="user.status === '禁用' ? '启用用户' : '禁用用户'">
                    <i :class="user.status === '禁用' ? 'fas fa-toggle-on' : 'fas fa-toggle-off'"></i>
                  </button>
                  <button @click="confirmDeleteUser(user)" class="btn btn-sm btn-danger" title="删除用户" aria-label="删除用户">
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-if="filteredUsers.length === 0 && !isLoading" class="no-data">
        <i class="fas fa-users-slash"></i>
        <p>没有找到符合条件的用户</p>
        <button @click="resetFilters" class="btn btn-primary">重置筛选</button>
      </div>

      <div class="table-footer">
        <div class="pagination-info">
          显示 {{ paginationInfo.start }}-{{ paginationInfo.end }} 条，共 {{ filteredUsers.length }} 条
        </div>
        <div class="pagination">
          <button
            @click="goToPage(1)"
            :disabled="currentPage === 1"
            class="btn btn-sm"
            aria-label="第一页"
          >
            <i class="fas fa-angle-double-left"></i>
          </button>
          <button
            @click="prevPage"
            :disabled="currentPage === 1"
            class="btn btn-sm"
            aria-label="上一页"
          >
            <i class="fas fa-angle-left"></i>
          </button>

          <div class="page-numbers">
            <button
              v-for="page in displayedPages"
              :key="page"
              @click="goToPage(page)"
              class="btn btn-sm"
              :class="{ 'btn-primary': currentPage === page }"
              :aria-label="`第 ${page} 页`"
              :aria-current="currentPage === page ? 'page' : undefined"
            >
              {{ page }}
            </button>
          </div>

          <button
            @click="nextPage"
            :disabled="currentPage === totalPages"
            class="btn btn-sm"
            aria-label="下一页"
          >
            <i class="fas fa-angle-right"></i>
          </button>
          <button
            @click="goToPage(totalPages)"
            :disabled="currentPage === totalPages"
            class="btn btn-sm"
            aria-label="最后一页"
          >
            <i class="fas fa-angle-double-right"></i>
          </button>
        </div>
        <div class="page-size-selector">
          <label for="page-size">每页显示:</label>
          <select
            id="page-size"
            v-model="itemsPerPage"
            @change="handlePageSizeChange"
            aria-label="选择每页显示数量"
          >
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
          </select>
        </div>
      </div>
    </div>

    <!-- User Form Modal -->
    <div v-if="showModal" class="modal" @click.self="closeModal">
      <div class="modal-content" role="dialog" aria-labelledby="userModalTitle">
        <div class="modal-header">
          <h3 id="userModalTitle">{{ editingUser ? '编辑用户' : '添加新用户' }}</h3>
          <button @click="closeModal" class="close-button" aria-label="关闭">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <form @submit.prevent="saveUser" class="user-form">
          <div class="form-grid">
            <div class="form-group">
              <label for="username">用户名 <span class="required">*</span></label>
              <input
                type="text"
                id="username"
                v-model="userForm.username"
                required
                :class="{ 'error': formErrors.username }"
                @input="validateField('username')"
                autocomplete="username"
              >
              <div v-if="formErrors.username" class="error-message">{{ formErrors.username }}</div>
            </div>

            <div class="form-group">
              <label for="email">邮箱 <span class="required">*</span></label>
              <input
                type="email"
                id="email"
                v-model="userForm.email"
                required
                :class="{ 'error': formErrors.email }"
                @input="validateField('email')"
                autocomplete="email"
              >
              <div v-if="formErrors.email" class="error-message">{{ formErrors.email }}</div>
            </div>

            <div class="form-group">
              <label for="role">角色 <span class="required">*</span></label>
              <select
                id="role"
                v-model="userForm.role"
                required
              >
                <option value="学生">学生</option>
                <option value="教师">教师</option>
                <option value="管理员">管理员</option>
              </select>
            </div>

            <div class="form-group">
              <label for="status">状态</label>
              <select id="status" v-model="userForm.status">
                <option value="活跃">活跃</option>
                <option value="禁用">禁用</option>
              </select>
            </div>

            <div v-if="!editingUser" class="form-group span-2">
              <label for="password">密码 <span class="required">*</span></label>
              <div class="password-input">
                <input
                  :type="showPassword ? 'text' : 'password'"
                  id="password"
                  v-model="userForm.password"
                  required
                  :class="{ 'error': formErrors.password }"
                  @input="validateField('password')"
                  autocomplete="new-password"
                >
                <button
                  type="button"
                  @click="togglePasswordVisibility"
                  class="toggle-password"
                  aria-label="切换密码可见性"
                >
                  <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                </button>
              </div>
              <div v-if="formErrors.password" class="error-message">{{ formErrors.password }}</div>
              <div class="password-strength" v-if="userForm.password">
                <div class="strength-meter">
                  <div
                    class="strength-value"
                    :style="{ width: passwordStrength.percentage + '%' }"
                    :class="passwordStrength.class"
                  ></div>
                </div>
                <span :class="'text-' + passwordStrength.class">{{ passwordStrength.text }}</span>
              </div>
              <div class="password-tips">
                密码应包含至少8个字符，包括大小写字母、数字和特殊字符
              </div>
            </div>

            <div class="form-group span-2">
              <label for="remarks">备注</label>
              <textarea
                id="remarks"
                v-model="userForm.remarks"
                rows="3"
                placeholder="可选的用户备注信息"
              ></textarea>
            </div>
          </div>

          <div class="form-actions">
            <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
            <button
              type="submit"
              class="btn btn-primary"
              :disabled="isSaving || !isFormValid"
            >
              <i v-if="isSaving" class="fas fa-spinner fa-spin"></i>
              <span v-else>保存</span>
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- User Details Modal -->
    <div v-if="showDetailsModal" class="modal" @click.self="showDetailsModal = false">
      <div class="modal-content user-details-modal" role="dialog" aria-labelledby="userDetailsTitle">
        <div class="modal-header">
          <h3 id="userDetailsTitle">用户详情</h3>
          <button @click="showDetailsModal = false" class="close-button" aria-label="关闭">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="user-details-content" v-if="selectedUserDetails">
          <div class="user-details-header">
            <div
              class="user-avatar large"
              :style="{ backgroundColor: getAvatarColor(selectedUserDetails.username) }"
            >
            <img src="http://localhost:3100/ZZZ.png" alt="">
              {{ getUserInitials(selectedUserDetails.username) }}
            </div>
            <div class="user-basic-info">
              <h2>{{ selectedUserDetails.username }}</h2>
              <p class="user-email">
                <i class="fas fa-envelope"></i> {{ selectedUserDetails.email }}
              </p>
              <div class="user-badges">
                <span :class="getRoleClass(selectedUserDetails.role)">
                  <i class="fas fa-user-tag"></i> {{ selectedUserDetails.role }}
                </span>
                <span :class="getStatusClass(selectedUserDetails.status)">
                  <i :class="selectedUserDetails.status === '活跃' ? 'fas fa-check-circle' : 'fas fa-ban'"></i>
                  {{ selectedUserDetails.status }}
                </span>
              </div>
            </div>
          </div>

          <div class="user-details-body">
            <div class="details-section">
              <h4><i class="fas fa-info-circle"></i> 基本信息</h4>
              <div class="details-grid">
                <div class="detail-item">
                  <span class="detail-label">用户ID</span>
                  <span class="detail-value">{{ selectedUserDetails.id }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">创建时间</span>
                  <span class="detail-value">{{ formatDate(selectedUserDetails.createdAt) }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">最后登录</span>
                  <span class="detail-value">{{ selectedUserDetails.lastLogin ? formatDate(selectedUserDetails.lastLogin) : '从未登录' }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">登录次数</span>
                  <span class="detail-value">{{ selectedUserDetails.loginCount || 0 }}</span>
                </div>
              </div>
            </div>

            <div class="details-section">
              <h4><i class="fas fa-clipboard-list"></i> 活动统计</h4>
              <div class="details-grid">
                <div class="detail-item">
                  <span class="detail-label">参与考试</span>
                  <span class="detail-value">{{ selectedUserDetails.examCount || 0 }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">平均分数</span>
                  <span class="detail-value">{{ selectedUserDetails.averageScore || 'N/A' }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">最高分数</span>
                  <span class="detail-value">{{ selectedUserDetails.highestScore || 'N/A' }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">最近活动</span>
                  <span class="detail-value">{{ selectedUserDetails.lastActivity ? formatDate(selectedUserDetails.lastActivity) : '无活动' }}</span>
                </div>
              </div>
            </div>

            <div class="details-section" v-if="selectedUserDetails.remarks">
              <h4><i class="fas fa-sticky-note"></i> 备注</h4>
              <p class="user-remarks">{{ selectedUserDetails.remarks }}</p>
            </div>
          </div>

          <div class="user-details-footer">
            <button @click="editUser(selectedUserDetails)" class="btn btn-secondary">
              <i class="fas fa-edit"></i> 编辑用户
            </button>
            <button @click="resetPassword(selectedUserDetails.id)" class="btn btn-warning">
              <i class="fas fa-key"></i> 重置密码
            </button>
            <button
              @click="toggleUserStatus(selectedUserDetails)"
              :class="selectedUserDetails.status === '禁用' ? 'btn btn-success' : 'btn btn-danger'"
            >
              <i :class="selectedUserDetails.status === '禁用' ? 'fas fa-toggle-on' : 'fas fa-toggle-off'"></i>
              {{ selectedUserDetails.status === '禁用' ? '启用用户' : '禁用用户' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Import Users Modal -->
    <div v-if="showImportModal" class="modal" @click.self="showImportModal = false">
      <div class="modal-content" role="dialog" aria-labelledby="importModalTitle">
        <div class="modal-header">
          <h3 id="importModalTitle">批量导入用户</h3>
          <button @click="showImportModal = false" class="close-button" aria-label="关闭">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="import-instructions">
            <h4><i class="fas fa-info-circle"></i> 导入说明</h4>
            <p>请上传包含用户数据的CSV文件，文件应包含以下列：</p>
            <ul>
              <li><strong>username</strong> - 用户名（必填）</li>
              <li><strong>email</strong> - 邮箱地址（必填）</li>
              <li><strong>role</strong> - 角色（学生/教师/管理员）</li>
              <li><strong>password</strong> - 初始密码</li>
            </ul>
            <p>您可以 <a href="#" @click.prevent="downloadTemplate">下载模板文件</a> 进行填写。</p>
          </div>

          <div class="file-upload-container">
            <div
              class="file-drop-zone"
              :class="{ 'active': isDragging }"
              @dragover.prevent="isDragging = true"
              @dragleave.prevent="isDragging = false"
              @drop.prevent="handleFileDrop"
            >
              <i class="fas fa-cloud-upload-alt"></i>
              <p>拖放CSV文件到此处，或</p>
              <label class="file-upload-btn">
                选择文件
                <input
                  type="file"
                  accept=".csv"
                  @change="handleFileSelect"
                  ref="fileInput"
                  style="display: none;"
                >
              </label>
            </div>

            <div v-if="importFile" class="selected-file">
              <i class="fas fa-file-csv"></i>
              <span>{{ importFile.name }}</span>
              <button @click="removeImportFile" class="btn btn-sm btn-danger" aria-label="移除文件">
                <i class="fas fa-times"></i>
              </button>
            </div>
          </div>

          <div v-if="importPreview.length > 0" class="import-preview">
            <h4>导入预览 ({{ importPreview.length }} 条记录)</h4>
            <div class="table-responsive">
              <table>
                <thead>
                  <tr>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>角色</th>
                    <th>状态</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(user, index) in importPreview.slice(0, 5)" :key="index">
                    <td>{{ user.username }}</td>
                    <td>{{ user.email }}</td>
                    <td>{{ user.role || '学生' }}</td>
                    <td>{{ user.status || '活跃' }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <p v-if="importPreview.length > 5" class="preview-more">
              还有 {{ importPreview.length - 5 }} 条记录未显示...
            </p>
          </div>

          <div v-if="importErrors.length > 0" class="import-errors">
            <h4><i class="fas fa-exclamation-triangle"></i> 导入错误</h4>
            <ul>
              <li v-for="(error, index) in importErrors" :key="index" class="error-item">
                {{ error }}
              </li>
            </ul>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showImportModal = false" class="btn btn-secondary">取消</button>
          <button
            @click="processImport"
            class="btn btn-primary"
            :disabled="!importFile || importPreview.length === 0 || isImporting"
          >
            <i v-if="isImporting" class="fas fa-spinner fa-spin"></i>
            <span v-else>导入用户</span>
          </button>
        </div>
      </div>
    </div>

    <!-- Confirmation Dialog -->
    <div v-if="showConfirmDialog" class="modal" @click.self="cancelConfirmation">
      <div class="modal-content confirmation-dialog" role="alertdialog" aria-labelledby="confirmDialogTitle">
        <div class="modal-header">
          <h3 id="confirmDialogTitle">{{ confirmDialogTitle }}</h3>
          <button @click="cancelConfirmation" class="close-button" aria-label="关闭">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="confirmation-icon" :class="confirmDialogType">
            <i :class="getConfirmationIcon()"></i>
          </div>
          <p>{{ confirmDialogMessage }}</p>
        </div>
        <div class="modal-footer">
          <button @click="cancelConfirmation" class="btn btn-secondary">取消</button>
          <button
            @click="confirmAction"
            class="btn"
            :class="'btn-' + confirmDialogType"
          >
            确认
          </button>
        </div>
      </div>
    </div>

    <!-- Toast Notifications -->
    <div class="toast-container">
      <div
        v-for="toast in toasts"
        :key="toast.id"
        class="toast"
        :class="toast.type"
        role="alert"
      >
        <div class="toast-icon">
          <i :class="getToastIcon(toast.type)"></i>
        </div>
        <div class="toast-content">
          <div class="toast-title">{{ toast.title }}</div>
          <div class="toast-message">{{ toast.message }}</div>
        </div>
        <button @click="removeToast(toast.id)" class="toast-close" aria-label="关闭通知">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';

// 模拟用户数据
const generateMockUsers = (count) => {
  const roles = ['学生', '教师', '管理员'];
  const statuses = ['活跃', '禁用'];
  const users = [];

  for (let i = 1; i <= count; i++) {
    const role = roles[Math.floor(Math.random() * roles.length)];
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const createdAt = new Date();
    createdAt.setDate(createdAt.getDate() - Math.floor(Math.random() * 365));

    users.push({
      id: i,
      username: `user${i}`,
      email: `user${i}@example.com`,
      role,
      status,
      createdAt: createdAt.toISOString(),
      lastLogin: Math.random() > 0.3 ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString() : null,
      loginCount: Math.floor(Math.random() * 50),
      examCount: role === '学生' ? Math.floor(Math.random() * 20) : null,
      averageScore: role === '学生' ? Math.floor(Math.random() * 40) + 60 : null,
      highestScore: role === '学生' ? Math.floor(Math.random() * 20) + 80 : null,
      lastActivity: Math.random() > 0.5 ? new Date(Date.now() - Math.random() * 14 * 24 * 60 * 60 * 1000).toISOString() : null,
      remarks: Math.random() > 0.7 ? `这是用户${i}的备注信息，包含一些额外的描述。` : ''
    });
  }

  return users;
};

// 状态变量
const users = ref([]);
const isLoading = ref(true);
const isSaving = ref(false);
const isImporting = ref(false);
const searchQuery = ref('');
const roleFilter = ref('');
const statusFilter = ref('');
const currentPage = ref(1);
const itemsPerPage = ref(10);
const sortColumn = ref('id');
const sortDirection = ref('asc');
const selectedUsers = ref([]);
const showModal = ref(false);
const showDetailsModal = ref(false);
const showImportModal = ref(false);
const showConfirmDialog = ref(false);
const editingUser = ref(null);
const selectedUserDetails = ref(null);
const showPassword = ref(false);
const isDragging = ref(false);
const importFile = ref(null);
const importPreview = ref([]);
const importErrors = ref([]);
const toasts = ref([]);

// 确认对话框状态
const confirmDialogTitle = ref('');
const confirmDialogMessage = ref('');
const confirmDialogType = ref('danger');
const confirmCallback = ref(null);

// 表单状态
const userForm = ref({
  username: '',
  email: '',
  role: '学生',
  status: '活跃',
  password: '',
  remarks: ''
});

const formErrors = ref({
  username: '',
  email: '',
  password: ''
});

// 加载用户数据
onMounted(async () => {
  try {
    isLoading.value = true;
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800));
    users.value = generateMockUsers(100);
  } catch (error) {
    console.error('加载用户数据失败:', error);
    showToast('error', '加载失败', '无法加载用户数据，请稍后重试');
  } finally {
    isLoading.value = false;
  }
});

// 计算属性
const filteredUsers = computed(() => {
  let result = [...users.value];

  // 应用搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(user =>
      user.username.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query) ||
      (user.remarks && user.remarks.toLowerCase().includes(query))
    );
  }

  // 应用角色过滤
  if (roleFilter.value) {
    result = result.filter(user => user.role === roleFilter.value);
  }

  // 应用状态过滤
  if (statusFilter.value) {
    result = result.filter(user => user.status === statusFilter.value);
  }

  // 应用排序
  result.sort((a, b) => {
    let valueA = a[sortColumn.value];
    let valueB = b[sortColumn.value];

    // 处理日期类型
    if (sortColumn.value === 'createdAt' || sortColumn.value === 'lastLogin') {
      valueA = valueA ? new Date(valueA).getTime() : 0;
      valueB = valueB ? new Date(valueB).getTime() : 0;
    }

    if (valueA < valueB) return sortDirection.value === 'asc' ? -1 : 1;
    if (valueA > valueB) return sortDirection.value === 'asc' ? 1 : -1;
    return 0;
  });

  return result;
});

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  const end = start + itemsPerPage.value;
  return filteredUsers.value.slice(start, end);
});

const totalPages = computed(() => {
  return Math.ceil(filteredUsers.value.length / itemsPerPage.value) || 1;
});

const displayedPages = computed(() => {
  const pages = [];
  const maxVisiblePages = 5;

  if (totalPages.value <= maxVisiblePages) {
    // 显示所有页码
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i);
    }
  } else {
    // 显示部分页码
    if (currentPage.value <= 3) {
      // 当前页靠近开始
      for (let i = 1; i <= 5; i++) {
        pages.push(i);
      }
    } else if (currentPage.value >= totalPages.value - 2) {
      // 当前页靠近结束
      for (let i = totalPages.value - 4; i <= totalPages.value; i++) {
        pages.push(i);
      }
    } else {
      // 当前页在中间
      for (let i = currentPage.value - 2; i <= currentPage.value + 2; i++) {
        pages.push(i);
      }
    }
  }

  return pages;
});

const paginationInfo = computed(() => {
  const start = filteredUsers.value.length === 0 ? 0 : (currentPage.value - 1) * itemsPerPage.value + 1;
  const end = Math.min(start + itemsPerPage.value - 1, filteredUsers.value.length);
  return { start, end };
});

const isAllSelected = computed(() => {
  return paginatedUsers.value.length > 0 && selectedUsers.value.length === paginatedUsers.value.length;
});

const isFormValid = computed(() => {
  if (editingUser.value) {
    return !formErrors.value.username && !formErrors.value.email;
  } else {
    return !formErrors.value.username && !formErrors.value.email && !formErrors.value.password && userForm.value.password;
  }
});

const passwordStrength = computed(() => {
  if (!userForm.value.password) {
    return { percentage: 0, class: 'weak', text: '无' };
  }

  const password = userForm.value.password;
  let strength = 0;

  // 长度检查
  if (password.length >= 8) strength += 25;

  // 包含小写字母
  if (/[a-z]/.test(password)) strength += 25;

  // 包含大写字母
  if (/[A-Z]/.test(password)) strength += 25;

  // 包含数字
  if (/[0-9]/.test(password)) strength += 15;

  // 包含特殊字符
  if (/[^A-Za-z0-9]/.test(password)) strength += 10;

  // 返回强度评级
  if (strength < 40) {
    return { percentage: strength, class: 'weak', text: '弱' };
  } else if (strength < 70) {
    return { percentage: strength, class: 'medium', text: '中' };
  } else {
    return { percentage: strength, class: 'strong', text: '强' };
  }
});

// 方法
const debouncedSearch = (() => {
  let timeout;
  return () => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      currentPage.value = 1;
    }, 300);
  };
})();

const resetFilters = () => {
  searchQuery.value = '';
  roleFilter.value = '';
  statusFilter.value = '';
  currentPage.value = 1;
};

const sortBy = (column) => {
  if (sortColumn.value === column) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
  } else {
    sortColumn.value = column;
    sortDirection.value = 'asc';
  }
};

const getSortIconClass = (column) => {
  if (sortColumn.value !== column) return '';
  return sortDirection.value === 'asc' ? 'fas fa-sort-up' : 'fas fa-sort-down';
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const goToPage = (page) => {
  currentPage.value = page;
};

const handlePageSizeChange = () => {
  currentPage.value = 1;
};

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedUsers.value = [];
  } else {
    selectedUsers.value = paginatedUsers.value.map(user => user.id);
  }
};

const toggleSelect = (userId) => {
  const index = selectedUsers.value.indexOf(userId);
  if (index === -1) {
    selectedUsers.value.push(userId);
  } else {
    selectedUsers.value.splice(index, 1);
  }
};

const isSelected = (userId) => {
  return selectedUsers.value.includes(userId);
};

const showAddUserModal = () => {
  editingUser.value = null;
  userForm.value = {
    username: '',
    email: '',
    role: '学生',
    status: '活跃',
    password: '',
    remarks: ''
  };
  formErrors.value = { username: '', email: '', password: '' };
  showModal.value = true;
};

const editUser = (user) => {
  editingUser.value = user;
  userForm.value = { ...user };
  formErrors.value = { username: '', email: '', password: '' };
  showModal.value = true;

  // 如果正在查看用户详情，关闭详情模态框
  if (showDetailsModal.value) {
    showDetailsModal.value = false;
  }
};

const closeModal = () => {
  showModal.value = false;
  editingUser.value = null;
  showPassword.value = false;
};

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const validateField = (field) => {
  formErrors.value[field] = '';

  if (field === 'username') {
    if (!userForm.value.username) {
      formErrors.value.username = '用户名不能为空';
    } else if (userForm.value.username.length < 3) {
      formErrors.value.username = '用户名至少需要3个字符';
    } else if (!editingUser.value) {
      // 检查用户名是否已存在（仅在创建新用户时）
      const exists = users.value.some(u => u.username === userForm.value.username);
      if (exists) {
        formErrors.value.username = '该用户名已被使用';
      }
    }
  }

  if (field === 'email') {
    if (!userForm.value.email) {
      formErrors.value.email = '邮箱不能为空';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userForm.value.email)) {
      formErrors.value.email = '请输入有效的邮箱地址';
    } else if (!editingUser.value) {
      // 检查邮箱是否已存在（仅在创建新用户时）
      const exists = users.value.some(u => u.email === userForm.value.email);
      if (exists) {
        formErrors.value.email = '该邮箱已被使用';
      }
    }
  }

  if (field === 'password' && !editingUser.value) {
    if (!userForm.value.password) {
      formErrors.value.password = '密码不能为空';
    } else if (userForm.value.password.length < 8) {
      formErrors.value.password = '密码至少需要8个字符';
    } else if (!/[A-Z]/.test(userForm.value.password) ||
               !/[a-z]/.test(userForm.value.password) ||
               !/[0-9]/.test(userForm.value.password)) {
      formErrors.value.password = '密码需包含大小写字母和数字';
    }
  }
};

const saveUser = async () => {
  // 验证所有字段
  validateField('username');
  validateField('email');
  if (!editingUser.value) {
    validateField('password');
  }

  if (!isFormValid.value) {
    return;
  }

  try {
    isSaving.value = true;

    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800));

    if (editingUser.value) {
      // 更新现有用户
      const index = users.value.findIndex(u => u.id === editingUser.value.id);
      if (index !== -1) {
        users.value[index] = {
          ...users.value[index],
          ...userForm.value
        };
        showToast('success', '更新成功', `用户 ${userForm.value.username} 已更新`);
      }
    } else {
      // 创建新用户
      const newId = Math.max(...users.value.map(u => u.id), 0) + 1;
      const newUser = {
        ...userForm.value,
        id: newId,
        createdAt: new Date().toISOString(),
        lastLogin: null,
        loginCount: 0
      };
      users.value.push(newUser);
      showToast('success', '创建成功', `用户 ${newUser.username} 已创建`);
    }

    closeModal();
  } catch (error) {
    console.error('保存用户失败:', error);
    showToast('error', '保存失败', '无法保存用户数据，请稍后重试');
  } finally {
    isSaving.value = false;
  }
};

const viewUserDetails = (user) => {
  selectedUserDetails.value = { ...user };
  showDetailsModal.value = true;
};

const resetPassword = (userId) => {
  showConfirmDialog.value = true;
  confirmDialogTitle.value = '重置密码';
  confirmDialogMessage.value = '确定要重置该用户的密码吗？新密码将发送到用户邮箱。';
  confirmDialogType.value = 'warning';
  confirmCallback.value = async () => {
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 800));

      const user = users.value.find(u => u.id === userId);
      if (user) {
        showToast('success', '密码已重置', `${user.username} 的新密码已发送到邮箱`);
      }
    } catch (error) {
      console.error('重置密码失败:', error);
      showToast('error', '操作失败', '无法重置密码，请稍后重试');
    }
  };
};

const toggleUserStatus = (user) => {
  const newStatus = user.status === '禁用' ? '活跃' : '禁用';
  const actionText = newStatus === '活跃' ? '启用' : '禁用';

  showConfirmDialog.value = true;
  confirmDialogTitle.value = `${actionText}用户`;
  confirmDialogMessage.value = `确定要${actionText}用户 ${user.username} 吗？`;
  confirmDialogType.value = newStatus === '活跃' ? 'success' : 'danger';
  confirmCallback.value = async () => {
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500));

      // 更新用户状态
      const index = users.value.findIndex(u => u.id === user.id);
      if (index !== -1) {
        users.value[index].status = newStatus;

        // 如果正在查看用户详情，更新详情中的状态
        if (selectedUserDetails.value && selectedUserDetails.value.id === user.id) {
          selectedUserDetails.value.status = newStatus;
        }

        showToast('success', '状态已更新', `用户 ${user.username} 已${actionText}`);
      }
    } catch (error) {
      console.error('更新用户状态失败:', error);
      showToast('error', '操作失败', `无法${actionText}用户，请稍后重试`);
    }
  };
};

const confirmDeleteUser = (user) => {
  showConfirmDialog.value = true;
  confirmDialogTitle.value = '删除用户';
  confirmDialogMessage.value = `确定要删除用户 ${user.username} 吗？此操作不可撤销。`;
  confirmDialogType.value = 'danger';
  confirmCallback.value = async () => {
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500));

      // 从选中列表中移除
      const selectedIndex = selectedUsers.value.indexOf(user.id);
      if (selectedIndex !== -1) {
        selectedUsers.value.splice(selectedIndex, 1);
      }

      // 从用户列表中移除
      users.value = users.value.filter(u => u.id !== user.id);

      showToast('success', '删除成功', `用户 ${user.username} 已删除`);
    } catch (error) {
      console.error('删除用户失败:', error);
      showToast('error', '删除失败', '无法删除用户，请稍后重试');
    }
  };
};

const confirmBatchDelete = () => {
  if (selectedUsers.value.length === 0) return;

  showConfirmDialog.value = true;
  confirmDialogTitle.value = '批量删除用户';
  confirmDialogMessage.value = `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可撤销。`;
  confirmDialogType.value = 'danger';
  confirmCallback.value = async () => {
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 800));

      // 批量删除用户
      users.value = users.value.filter(user => !selectedUsers.value.includes(user.id));
      selectedUsers.value = [];

      showToast('success', '批量删除成功', `已删除 ${selectedUsers.value.length} 个用户`);
    } catch (error) {
      console.error('批量删除用户失败:', error);
      showToast('error', '操作失败', '无法批量删除用户，请稍后重试');
    }
  };
};

const confirmAction = async () => {
  if (confirmCallback.value) {
    await confirmCallback.value();
  }
  cancelConfirmation();
};

const cancelConfirmation = () => {
  showConfirmDialog.value = false;
  confirmDialogTitle.value = '';
  confirmDialogMessage.value = '';
  confirmCallback.value = null;
};

const getConfirmationIcon = () => {
  switch (confirmDialogType.value) {
    case 'danger': return 'fas fa-trash-alt';
    case 'warning': return 'fas fa-exclamation-triangle';
    case 'success': return 'fas fa-check-circle';
    default: return 'fas fa-question-circle';
  }
};

const handleFileSelect = (event) => {
  const file = event.target.files[0];
  if (file) {
    processFile(file);
  }
};

const handleFileDrop = (event) => {
  isDragging.value = false;
  const file = event.dataTransfer.files[0];
  if (file && file.type === 'text/csv') {
    processFile(file);
  } else {
    showToast('error', '文件类型错误', '请上传CSV文件');
  }
};

const processFile = (file) => {
  importFile.value = file;
  importErrors.value = [];

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const csv = e.target.result;
      const lines = csv.split('\n');
      const headers = lines[0].split(',').map(h => h.trim());

      // 验证必要的列
      if (!headers.includes('username') || !headers.includes('email')) {
        importErrors.value.push('CSV文件缺少必要的列：username 和 email');
        importPreview.value = [];
        return;
      }

      // 解析数据
      const users = [];
      for (let i = 1; i < lines.length; i++) {
        if (!lines[i].trim()) continue;

        const values = lines[i].split(',').map(v => v.trim());
        const user = {};

        headers.forEach((header, index) => {
          if (index < values.length) {
            user[header] = values[index];
          }
        });

        // 验证必填字段
        if (!user.username || !user.email) {
          importErrors.value.push(`第 ${i} 行：用户名和邮箱不能为空`);
          continue;
        }

        // 验证邮箱格式
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(user.email)) {
          importErrors.value.push(`第 ${i} 行：邮箱格式不正确 (${user.email})`);
          continue;
        }

        // 设置默认值
        user.role = user.role || '学生';
        user.status = user.status || '活跃';

        users.push(user);
      }

      importPreview.value = users;

      if (users.length === 0) {
        importErrors.value.push('没有有效的用户数据');
      }
    } catch (error) {
      console.error('解析CSV文件失败:', error);
      importErrors.value.push('解析CSV文件失败，请检查文件格式');
      importPreview.value = [];
    }
  };

  reader.readAsText(file);
};

const removeImportFile = () => {
  importFile.value = null;
  importPreview.value = [];
  importErrors.value = [];
  if (this.$refs.fileInput) {
    this.$refs.fileInput.value = '';
  }
};

const downloadTemplate = () => {
  const headers = 'username,email,role,password,status\n';
  const exampleData = 'user1,user1@example.com,学生,password123,活跃\n' +
                      'user2,user2@example.com,教师,password456,活跃\n';
  const csvContent = headers + exampleData;

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'user_import_template.csv');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const processImport = async () => {
  if (!importFile.value || importPreview.value.length === 0) return;

  try {
    isImporting.value = true;

    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1500));

    // 添加用户
    const newUsers = [];
    let lastId = Math.max(...users.value.map(u => u.id), 0);

    for (const userData of importPreview.value) {
      lastId++;
      newUsers.push({
        id: lastId,
        username: userData.username,
        email: userData.email,
        role: userData.role || '学生',
        status: userData.status || '活跃',
        createdAt: new Date().toISOString(),
        lastLogin: null,
        loginCount: 0
      });
    }

    users.value = [...users.value, ...newUsers];

    showToast('success', '导入成功', `成功导入 ${newUsers.length} 个用户`);
    showImportModal.value = false;
    removeImportFile();
  } catch (error) {
    console.error('导入用户失败:', error);
    showToast('error', '导入失败', '无法导入用户，请稍后重试');
  } finally {
    isImporting.value = false;
  }
};

const exportUsers = () => {
  // 确定要导出的用户
  let usersToExport = [];

  if (selectedUsers.value.length > 0) {
    // 导出选中的用户
    usersToExport = users.value.filter(user => selectedUsers.value.includes(user.id));
  } else {
    // 导出当前筛选的所有用户
    usersToExport = filteredUsers.value;
  }

  if (usersToExport.length === 0) {
    showToast('warning', '导出失败', '没有可导出的用户');
    return;
  }

  // 创建CSV内容
  const headers = ['id', 'username', 'email', 'role', 'status', 'createdAt'].join(',');
  const rows = usersToExport.map(user => {
    return [
      user.id,
      user.username,
      user.email,
      user.role,
      user.status,
      user.createdAt
    ].join(',');
  });

  const csvContent = [headers, ...rows].join('\n');

  // 创建下载链接
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', `users_export_${new Date().toISOString().slice(0, 10)}.csv`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  showToast('success', '导出成功', `已导出 ${usersToExport.length} 个用户`);
};

// 辅助函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};

const getUserInitials = (name) => {
  if (!name) return '';
  return name.charAt(0).toUpperCase();
};

const getAvatarColor = (username) => {
  if (!username) return '#1890ff';

  // 根据用户名生成一致的颜色
  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = username.charCodeAt(i) + ((hash << 5) - hash);
  }

  const colors = [
    '#1890ff', '#52c41a', '#722ed1', '#fa8c16', '#eb2f96',
    '#13c2c2', '#faad14', '#a0d911', '#f5222d', '#2f54eb'
  ];

  return colors[Math.abs(hash) % colors.length];
};

const getRoleClass = (role) => {
  switch (role) {
    case '学生': return 'role-student';
    case '教师': return 'role-teacher';
    case '管理员': return 'role-admin';
    default: return '';
  }
};

const getStatusClass = (status) => {
  return status === '活跃' ? 'status-active' : 'status-disabled';
};

const showToast = (type, title, message) => {
  const id = Date.now();
  toasts.value.push({ id, type, title, message });

  // 自动关闭
  setTimeout(() => {
    removeToast(id);
  }, 5000);
};

const removeToast = (id) => {
  const index = toasts.value.findIndex(toast => toast.id === id);
  if (index !== -1) {
    toasts.value.splice(index, 1);
  }
};

const getToastIcon = (type) => {
  switch (type) {
    case 'success': return 'fas fa-check-circle';
    case 'error': return 'fas fa-times-circle';
    case 'warning': return 'fas fa-exclamation-triangle';
    case 'info': return 'fas fa-info-circle';
    default: return 'fas fa-bell';
  }
};

// 监听筛选条件变化，重置页码
watch([searchQuery, roleFilter, statusFilter], () => {
  currentPage.value = 1;
});
</script>

<style scoped>
.users-management {
  padding: 1rem;
  background-color: var(--component-background);
  border-radius: 8px;
  box-shadow: 0 2px 4px var(--shadow-color);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.page-title {
  font-size: 1.5rem;
  margin: 0;
  color: var(--primary);
  border-bottom: 2px solid var(--primary);
  padding-bottom: 0.5rem;
}

.page-actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.search-box {
  position: relative;
  flex-grow: 1;
  max-width: 300px;
}

.search-box input {
  width: 100%;
  padding: 0.5rem 0.5rem 0.5rem 2rem;
  border: 1px solid var(--border);
  border-radius: 4px;
  font-size: 1rem;
  background-color: var(--component-background);
  color: var(--text);
}

.search-box i {
  position: absolute;
  left: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-secondary);
}

.filter-controls {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.role-filter,
.status-filter {
  padding: 0.5rem;
  border: 1px solid var(--border);
  border-radius: 4px;
  font-size: 1rem;
  background-color: var(--component-background);
  color: var(--text);
}

.btn-outline {
  background-color: transparent;
  border: 1px solid var(--border);
  color: var(--text);
}

.btn-outline:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.dark .btn-outline:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.table-container {
  position: relative;
  margin-top: 1rem;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
  border-radius: 4px;
}

.dark .loading-overlay {
  background-color: rgba(0, 0, 0, 0.7);
}

.spinner {
  font-size: 2rem;
  color: var(--primary);
  margin-bottom: 1rem;
}

.table-responsive {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 1rem;
  color: var(--text);
}

th, td {
  border: 1px solid var(--border);
  padding: 0.75rem;
  text-align: left;
}

th {
  background-color: rgba(0, 0, 0, 0.02);
  font-weight: bold;
  color: var(--primary);
  position: relative;
}

.dark th {
  background-color: rgba(255, 255, 255, 0.05);
}

th.sortable {
  cursor: pointer;
}

th.sortable:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.dark th.sortable:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

th i {
  margin-left: 0.5rem;
}

tr:nth-child(even) {
  background-color: rgba(0, 0, 0, 0.01);
}

.dark tr:nth-child(even) {
  background-color: rgba(255, 255, 255, 0.02);
}

tr:hover {
  background-color: rgba(0, 0, 0, 0.03);
}

.dark tr:hover {
  background-color: rgba(255, 255, 255, 0.05);
}

tr.selected-row {
  background-color: rgba(24, 144, 255, 0.1);
}

.dark tr.selected-row {
  background-color: rgba(24, 144, 255, 0.2);
}

.checkbox-column {
  width: 40px;
  text-align: center;
}

.checkbox-container {
  position: relative;
  display: inline-block;
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.checkbox-container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 18px;
  width: 18px;
  background-color: var(--component-background);
  border: 1px solid var(--border);
  border-radius: 3px;
}

.checkbox-container:hover input ~ .checkmark {
  background-color: rgba(0, 0, 0, 0.05);
}

.dark .checkbox-container:hover input ~ .checkmark {
  background-color: rgba(255, 255, 255, 0.1);
}

.checkbox-container input:checked ~ .checkmark {
  background-color: var(--primary);
  border-color: var(--primary);
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox-container input:checked ~ .checkmark:after {
  display: block;
}

.checkbox-container .checkmark:after {
  left: 6px;
  top: 2px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.user-avatar.large {
  width: 80px;
  height: 80px;
  font-size: 2rem;
}

.role-student, .role-teacher, .role-admin,
.status-active, .status-disabled {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
  display: inline-block;
}

.role-student { background-color: rgba(24, 144, 255, 0.1); color: #1890ff; }
.role-teacher { background-color: rgba(250, 140, 22, 0.1); color: #fa8c16; }
.role-admin { background-color: rgba(82, 196, 26, 0.1); color: #52c41a; }

.dark .role-student { background-color: rgba(24, 144, 255, 0.2); color: #40a9ff; }
.dark .role-teacher { background-color: rgba(250, 140, 22, 0.2); color: #ffa940; }
.dark .role-admin { background-color: rgba(82, 196, 26, 0.2); color: #73d13d; }

.status-active { background-color: rgba(82, 196, 26, 0.1); color: #52c41a; }
.status-disabled { background-color: rgba(245, 34, 45, 0.1); color: #f5222d; }

.dark .status-active { background-color: rgba(82, 196, 26, 0.2); color: #73d13d; }
.dark .status-disabled { background-color: rgba(245, 34, 45, 0.2); color: #ff4d4f; }

.action-buttons {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  justify-content: center;
}

.no-data {
  text-align: center;
  padding: 3rem;
  background-color: var(--component-background);
  border-radius: 8px;
  margin-top: 1rem;
  color: var(--text-secondary);
}

.no-data i {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.page-numbers {
  display: flex;
  gap: 0.25rem;
}

.pagination-info {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.page-size-selector label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.page-size-selector select {
  padding: 0.25rem 0.5rem;
  border: 1px solid var(--border);
  border-radius: 4px;
  background-color: var(--component-background);
  color: var(--text);
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--component-background);
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  color: var(--text);
  box-shadow: 0 4px 12px var(--shadow-color);
}

.user-details-modal {
  max-width: 700px;
}

.confirmation-dialog {
  max-width: 400px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid var(--border);
}

.modal-header h3 {
  margin: 0;
  font-size: 1.2rem;
}

.close-button {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: var(--text-secondary);
}

.modal-body {
  padding: 1rem;
  overflow-y: auto;
  flex-grow: 1;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  padding: 1rem;
  border-top: 1px solid var(--border);
}

.user-form {
  padding: 1rem;
  overflow-y: auto;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group.span-2 {
  grid-column: span 2;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: var(--text);
}

.required {
  color: var(--error);
  margin-left: 0.25rem;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid var(--border);
  border-radius: 4px;
  font-size: 1rem;
  background-color: var(--component-background);
  color: var(--text);
}

.form-group input.error,
.form-group select.error,
.form-group textarea.error {
  border-color: var(--error);
}

.error-message {
  color: var(--error);
  font-size: 0.8rem;
  margin-top: 0.25rem;
}

.password-input {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  color: var(--text-secondary);
}

.password-strength {
  margin-top: 0.5rem;
}

.strength-meter {
  height: 4px;
  background-color: #e9ecef;
  border-radius: 2px;
  margin-bottom: 0.25rem;
}

.strength-value {
  height: 100%;
  border-radius: 2px;
  transition: width 0.3s;
}

.strength-value.weak { background-color: #f5222d; }
.strength-value.medium { background-color: #faad14; }
.strength-value.strong { background-color: #52c41a; }

.text-weak { color: #f5222d; }
.text-medium { color: #faad14; }
.text-strong { color: #52c41a; }

.password-tips {
  font-size: 0.8rem;
  color: var(--text-secondary);
  margin-top: 0.25rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border);
}

.user-details-content {
  padding: 1rem;
  overflow-y: auto;
}

.user-details-header {
  display: flex;
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.user-basic-info {
  flex-grow: 1;
}

.user-basic-info h2 {
  margin: 0 0 0.5rem 0;
  color: var(--text);
}

.user-email {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: var(--text-secondary);
  margin-bottom: 1rem;
}

.user-badges {
  display: flex;
  gap: 0.5rem;
}

.user-details-body {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.details-section {
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 1rem;
}

.details-section h4 {
  margin-top: 0;
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: var(--primary);
}

.details-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 0.8rem;
  color: var(--text-secondary);
  margin-bottom: 0.25rem;
}

.detail-value {
  font-weight: 500;
}

.user-remarks {
  white-space: pre-line;
  color: var(--text);
}

.user-details-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border);
}

.import-instructions {
  margin-bottom: 1.5rem;
}

.import-instructions h4 {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0;
}

.import-instructions ul {
  margin: 0.5rem 0;
  padding-left: 1.5rem;
}

.file-upload-container {
  margin-bottom: 1.5rem;
}

.file-drop-zone {
  border: 2px dashed var(--border);
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.file-drop-zone.active {
  border-color: var(--primary);
  background-color: rgba(24, 144, 255, 0.05);
}

.file-drop-zone i {
  font-size: 2rem;
  color: var(--text-secondary);
  margin-bottom: 1rem;
}

.file-upload-btn {
  display: inline-block;
  margin-top: 0.5rem;
  padding: 0.5rem 1rem;
  background-color: var(--primary);
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.file-upload-btn:hover {
  background-color: var(--primary-dark);
}

.selected-file {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 1rem;
  padding: 0.5rem;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.dark .selected-file {
  background-color: rgba(255, 255, 255, 0.05);
}

.selected-file i {
  color: var(--primary);
}

.import-preview {
  margin-top: 1.5rem;
}

.import-preview h4 {
  margin-top: 0;
  margin-bottom: 0.5rem;
}

.preview-more {
  text-align: center;
  color: var(--text-secondary);
  font-style: italic;
}

.import-errors {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: rgba(245, 34, 45, 0.05);
  border-radius: 8px;
}

.import-errors h4 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: var(--error);
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.import-errors ul {
  margin: 0;
  padding-left: 1.5rem;
}

.error-item {
  color: var(--error);
  margin-bottom: 0.25rem;
}

.confirmation-icon {
  font-size: 3rem;
  text-align: center;
  margin-bottom: 1rem;
}

.confirmation-icon.danger { color: var(--error); }
.confirmation-icon.warning { color: var(--warning); }
.confirmation-icon.success { color: var(--success); }

.toast-container {
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  z-index: 2000;
  max-width: 350px;
}

.toast {
  display: flex;
  align-items: flex-start;
  padding: 1rem;
  border-radius: 4px;
  background-color: var(--component-background);
  box-shadow: 0 4px 12px var(--shadow-color);
  animation: toast-in 0.3s ease;
}

.toast.success { border-left: 4px solid var(--success); }
.toast.error { border-left: 4px solid var(--error); }
.toast.warning { border-left: 4px solid var(--warning); }
.toast.info { border-left: 4px solid var(--primary); }

.toast-icon {
  margin-right: 0.75rem;
  font-size: 1.2rem;
}

.toast.success .toast-icon { color: var(--success); }
.toast.error .toast-icon { color: var(--error); }
.toast.warning .toast-icon { color: var(--warning); }
.toast.info .toast-icon { color: var(--primary); }

.toast-content {
  flex-grow: 1;
}

.toast-title {
  font-weight: bold;
  margin-bottom: 0.25rem;
}

.toast-message {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.toast-close {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 0.25rem;
  margin-left: 0.5rem;
}

@keyframes toast-in {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-section {
    flex-direction: column;
  }

  .search-box {
    max-width: none;
    width: 100%;
  }

  .filter-controls {
    width: 100%;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .form-group.span-2 {
    grid-column: span 1;
  }

  .user-details-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .details-grid {
    grid-template-columns: 1fr;
  }

  .table-footer {
    flex-direction: column;
    align-items: center;
  }

  .toast-container {
    left: 1rem;
    right: 1rem;
    max-width: none;
  }
}
</style>

